package cn.yotta.user.core.server.service.impl;

import cn.yotta.user.api.params.login.BaseLoginRequest;
import cn.yotta.user.api.params.user.UserFindByTokenRequest;
import cn.yotta.user.api.vo.TokenVo;
import cn.yotta.user.api.vo.UserVo;
import cn.yotta.user.core.server.converter.UserConverter;
import cn.yotta.user.core.server.dto.token.TokenDto;
import cn.yotta.user.core.server.dto.user.UserDto;
import cn.yotta.user.core.server.manager.login.LoginManager;
import cn.yotta.user.core.server.manager.token.TokenManager;
import cn.yotta.user.core.server.properties.LoginTokenExpireTimeProperties;
import cn.yotta.user.core.server.service.LoginService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author wyaoyao
 * @date 2022/11/8 18:01
 */
@Service
@Slf4j
@AllArgsConstructor
public class LoginServiceImpl implements LoginService {

    private final LoginManager loginManager;

    private final TokenManager tokenManager;

    private final UserConverter userConverter;

    private final LoginTokenExpireTimeProperties loginTokenExpireTimeProperties;

    @Override
    public TokenVo login(BaseLoginRequest request) {
        final UserDto authUser = loginManager.auth(request);
        // 授权成功之后， 生成token
        // 推断token过期时间
        Integer expireTimeSecond = extrapolateTokenExpireTime(request);
        final TokenDto token = tokenManager.generate(authUser, expireTimeSecond);
        return convert(token);
    }


    @Override
    public UserVo getLoginUser(UserFindByTokenRequest request) {
        UserDto userDto = tokenManager.findLoginUserByToken(request.getToken());
        return userConverter.dto2Vo(userDto);
    }

    @Override
    public Boolean logout(UserFindByTokenRequest userFindByTokenRequest) {
        this.tokenManager.loginOut(userFindByTokenRequest.getToken());
        return Boolean.TRUE;
    }

    private TokenVo convert(TokenDto token) {
        return TokenVo.builder()
                .token(token.getToken())
                .expireSecond(token.getExpireSecond())
                .build();
    }

    /**
     * 推断token过期时间
     *
     * @param request 登录的请求参数
     * @return 返回token的过期时间
     * 比如说APP登录的过期时间一般会比pc登录的过期时间更长
     */
    protected Integer extrapolateTokenExpireTime(BaseLoginRequest request) {
        if (request.getIsApp()) {
            return loginTokenExpireTimeProperties.getApp();
        }
        return loginTokenExpireTimeProperties.getPc();
    }

}
